package com.hxw.sample.opengl30.uitls;

import android.content.Context;
import android.opengl.GLES30;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ShaderUtil {

    public static String getRawResource(Context context, int rawId)
    {
        InputStream inputStream = context.getResources().openRawResource(rawId);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        String line;
        try
        {
            while((line = reader.readLine()) != null)
            {
                sb.append(line).append("\n");
            }
            reader.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 加载并编译shader脚本
     * @param shaderType 脚本类型（顶点或纹理）
     * @param source 源码
     * @return 脚本ID
     */
    private static int loadShader(int shaderType, String source)
    {
        int shader = GLES30.glCreateShader(shaderType);
        if(shader != 0)
        {
            GLES30.glShaderSource(shader, source);
            GLES30.glCompileShader(shader);

            int[] compile = new int[1];
            GLES30.glGetShaderiv(shader, GLES30.GL_COMPILE_STATUS, compile, 0);
            if(compile[0] != GLES30.GL_TRUE)
            {
                Log.d("ywl5320", "shader compile error");
                shader = 0;
            }
            return shader;
        }
        else
        {
            return 0;
        }
    }

    /**
     * 创建渲染程序
     * @param vertexSource 顶点着色器 源码
     * @param fragmentSource 纹理着色器 源码
     * @return 渲染程序ID
     */
    public static int createProgram(String vertexSource, String fragmentSource)
    {
        int vertexShader = loadShader(GLES30.GL_VERTEX_SHADER, vertexSource);
        int fragmentShader = loadShader(GLES30.GL_FRAGMENT_SHADER, fragmentSource);

        if(vertexShader != 0 && fragmentShader != 0)
        {
            int program = GLES30.glCreateProgram();

            GLES30.glAttachShader(program, vertexShader);
            GLES30.glAttachShader(program, fragmentShader);

            GLES30.glLinkProgram(program);

            GLES30.glDeleteShader(vertexShader);//释放资源
            GLES30.glDeleteShader(fragmentShader);//释放资源
            return program;
        }
        return 0;
    }
}
